<?php

namespace App\Models\Train\TrainTripInfo\Repositories;

use App\Models\Train\TrainTripInfo\TrainTripInfo;
use App\Trip\Repository\BaseRepository;
use Exception;
use Illuminate\Support\Facades\Cache;
use JetBrains\PhpStorm\Pure;

class TrainTripInfoRepository extends BaseRepository implements Interfaces\TrainTripInfoRepositoryInterface
{

    #[Pure] public function __construct(TrainTripInfo $train_trip_info)
    {
        parent::__construct($train_trip_info);
    }

    /**
     * @throws Exception
     */
    public function addTrainTripInfo($data): TrainTripInfo
    {
        $train = $this->findOneByTrainAndStation($data['train_code'], $data['from_station_code'], $data['to_station_code']);
        if ($train) {
            return $train;
        }
        return $this->create($data);
    }


    /**
     * @inheritDoc
     */
    public function findOneByTrainAndStation(string $train_code, string $from_station_code, string $to_station_code): ?TrainTripInfo
    {
        $cache_key = "Train:TripInfo:{$train_code}:{$from_station_code}:{$to_station_code}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }
        $trip_info = $this->findOneBy([
            'train_code'        => $train_code,
            'from_station_code' => $from_station_code,
            'to_station_code'   => $to_station_code,
        ]);

        if ($trip_info instanceof TrainTripInfo) {
            Cache::put($cache_key, $trip_info, 10 * config('trip.ttl.day'));
        }
        return $trip_info;
    }
}